<?php

namespace app\admin\controller\microend;

use app\common\library\Auth;
use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 派克管理
 *
 * @icon fa fa-user
 */
class Paike extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $user_attribute = null;
    protected $user_real = null;
    protected $user_healthy = null;
    protected $auth_real = null;
    protected $noNeedRight = ['edit'];
    protected $multiFields = 'status,black';

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'uid,username,mobile';


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\User;
        $this->user_attribute = new \app\common\model\user\Attribute;
        $this->user_real = new \app\common\model\user\Real;
        $this->user_healthy = new \app\common\model\user\Healthy;
        $this->auth_real = new \app\common\model\auth\Real;
        $this->view->assign("healthyList", $this->model->getHealthyList());
        $this->view->assign("blackList", $this->model->getBlackList());
        $this->view->assign("roleList", $this->model->getRoleList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $join[] = ["sd_user_attribute e","e.uid = a.uid","left"];

            $join[] = ["sd_user_real l","l.uid = a.uid ","left"];

            $join[] = ["sd_user_healthy y","y.uid = a.uid","left"];

            $join[] = ["sd_auth_real d","d.uid = a.uid","left"];

            $field = "a.uid,a.username_alias,a.username,a.tao_bao_no,a.tao_bao_id,a.mobile,a.role,a.balance,a.status,a.black,a.reg_time,a.uid,a.uid as id,a.group_created_time";//user用户字段

            $field .= ",e.account_status,e.user_count,e.person_count,e.task_count,e.month_task_count,e.task_limit_cash,e.single_status,e.cash_status,e.task_status,e.task_finish_count,e.task_day_count,e.group_time";//user_attribute 字段


            $field .= ",l.real_status";//user_real 字段

            $field .= ",d.auth_status";//auth_real 字段身份证审核


            $field .= ",y.healthy";//user_healthy 字段


            //halt($where);


            $total = $this->model
                ->alias("a")
                ->join($join)
                ->where($where)
                //->order($sort, $order)
                ->count();

            //echo $this->model->getLastSql();exit;


//            $list = $this->model
//                ->with('userAttribute,userReal,userHealthy,authReal')
//                ->field('*,uid as id')
//                ->where($where)
//                ->order($sort, $order)
//                ->limit($offset, $limit)
//                ->select();
            $list = $this->model
                    ->alias("a")
                    ->join($join)
                    ->field($field)
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            //echo $this->model->getLastSql();exit;
            $list = collection($list)->toArray();
            foreach ($list as &$value){
                $value["d.auth_status"] = $value["auth_status"];
                $value["a.username"] = $value["username"];
                $value["a.username_alias"] = $value["username_alias"];
                $value["a.tao_bao_no"] = $value["tao_bao_no"];
                $value["a.mobile"] = $value["mobile"];
                $value["e.single_status"] = $value["single_status"];
                $value["e.cash_status"] = $value["cash_status"];
                $value["e.task_status"] = $value["task_status"];
                $value["e.account_status"] = $value["account_status"];
                $value["a.create_time"] = $value["create_time"];
                $value["l.real_status"] = $value["real_status"];
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $admin = session('admin');
        $group_info =  model('AuthGroupAccess')->where('uid',$admin['id'])->find();
        $rules_t = model('AuthGroup')->where('id',$group_info['group_id'])->value("rules");
        $rules = explode(",",$rules_t);
        if($rules_t!='*') {
            $rule_name = model('AuthRule')->where('id', 'in', $rules)->column("name");
            //halt($rule_name);
            if (!in_array('microend/paike/edit', $rule_name)) {
                $this->error(__('You have no permission'));
            }
        }
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            //halt($params);exit;
            if ($params) {
                $tao_bao_no = $params["tao_bao_no"];
                $mobile = $params["mobile"];
                $qq = $params["qq"];
                //$_where = " 1=1 AND ( `tao_bao_no` = '$tao_bao_no' or `mobile` = '$mobile' or `qq` = '$qq' ) ";
//                $_where["tao_bao_no"] = array(['eq',$tao_bao_no],'or');
//                $_where["mobile"] = array(['eq',$mobile],'or');
//                $_where["qq"] = array(['eq',$qq],'or');
                $_where = function($q) use ($tao_bao_no,$mobile,$qq){
                    $q->whereOr("tao_bao_no",$tao_bao_no);
                    $q->whereOr("mobile",$mobile);
                    $q->whereOr("qq",$qq);

                };
                $paike = $this->model
                    ->where($_where)
                    ->where("uid", "neq", $ids)
                    ->find();



                if ($paike) {
                    $this->error("手机，淘宝号，qq已注册");
                }

                if($row["userAttribute"]->user_count>$params["person_count"]){
                    $this->error("可招募人数不能小于已招募数");
                }


                Db::startTrans();
                //user表更改
                $_input_user = [
                    "username" => $params["username"],
                    "tao_bao_no" => $params["tao_bao_no"],
                    "mobile" => $params["mobile"],
                    "qq" => $params["qq"],
                    "role"=>$params["role"]
                    //"healthy"=>$params["healthy"]
                ];
                if(!$params["role"]){
                    $_input_user["role"] = "grouper";
                }
                if ($params["referrer_id"]) {
                    $_input_user["referrer_id"] = $params["referrer_id"];
                }

                $this->model->where(["uid" => $ids])->update($_input_user);


                $_input_healthy = [
                    "healthy" => $params["healthy"],
                ];
                $this->user_healthy->save($_input_healthy, ['uid' => $ids]);//修改user_healthy

                //user_attribute表更改
                $_input_user_attr = [
                    "card_no" => $params["card_no"],
                    "bank_name" => $params["bank_name"],
                    "bank_no" => $params["bank_no"],
                    "task_count" => $params["task_count"],
                    "month_task_count" => $params["month_task_count"],
                    "task_day_count" => $params["task_day_count"],
                    "task_limit_cash" => $params["task_limit_cash"],
                    "person_count" => $params["person_count"],
                    "address" => $params["address"],
                    "room" => $params["room"],
                    "single_status" => $params["single_status"],
                    "cash_status" => $params["cash_status"],
                    "task_status" => $params["task_status"],
                    "wx_code" => $params["wx_code"]
                ];
                $op = $this->user_attribute->where(["uid" => $ids])->setField($_input_user_attr);

                //更新银行卡信息
                $bank_input = [
                    "bank_person"=>$params["username"],
                    "bank_name"=>$params["bank_name"],
                    "bank_code"=>$params["bank_no"],
                    "updated_time"=>time()
                ];
                Db::name("user_bank")->where(["uid" => $ids])->setField($bank_input);
                Db::commit();
                $this->success();


            }

            $this->error();
        }
        //halt($row["userReal"]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $tao_bao_no = $params["tao_bao_no"];
                $mobile = $params["mobile"];
                $qq = $params["qq"];
                $_where = function($q) use ($tao_bao_no,$mobile,$qq){
                    $q->whereOr("tao_bao_no",$tao_bao_no);
                    $q->whereOr("mobile",$mobile);
                    $q->whereOr("qq",$qq);

                };
//                $_where = " 1=1 AND ( tao_bao_no = '$tao_bao_no' or mobile = '$mobile' or qq = '$qq' ) ";
                $paike = model("user")
                    ->where($_where)
                    ->find();
                if ($paike) {
                    $this->error("手机，淘宝号，qq已注册");
                }

                //user表更改
                $_input_user = [
                    "username" => $params["username"],
                    "tao_bao_no" => $params["tao_bao_no"],
                    "mobile" => $params["mobile"],
                    "qq" => $params["qq"],
                    "role" => $params["role"],
                    "reg_time" => time(),
                    //"reg_ip"=>0
                    //"healthy"=>$params["healthy"]
                ];
                if ($params["referrer_id"]) {
                    $_input_user["referrer_id"] = $params["referrer_id"];
                }


                Db::startTrans();

                $t_uid = $this->model->add($_input_user);//添加user


                $_input_healthy = [
                    "healthy" => $params["healthy"],
                    "uid" => $t_uid,
                    //"username" => $params["username"],
                    //"tao_bao_no" => $params["tao_bao_no"],
                   // "mobile" => $params["mobile"],
                    "tao_bao_info_img"=>"",
                    "on_time"=>time()
                ];
                $this->user_healthy->save($_input_healthy);//修改user_healthy

                if ($t_uid) {
                    //user_attribute表更改
                    $_input_user_attr = [
                        "card_no" => $params["card_no"],
                        "bank_name" => $params["bank_name"],
                        "bank_no" => $params["bank_no"],
                        "task_count" => $params["task_count"],
                        "month_task_count" => $params["month_task_count"],
                        "task_day_count" => $params["task_day_count"],
                        "task_limit_cash" => $params["task_limit_cash"],
                        "person_count" => $params["person_count"],
                        "address" => $params["address"],
                        "room" => $params["room"],
                        "single_status" => $params["single_status"],
                        "cash_status" => $params["cash_status"],
                        "task_status" => $params["task_status"],
                        "wx_code" => $params["wx_code"],
                        "uid" => $t_uid
                    ];
                    $op = 0;
                    $user_attr = Db::name('user_attribute')->where(["uid" => $t_uid])->find();
                    if ($user_attr) {
                        $op = $this->user_attribute->add_or_up($_input_user_attr, ["uid" => $t_uid]);
                    } else {
                        $op = $this->user_attribute->add_or_up($_input_user_attr);
                    }

                    $bank_input = [
                        "bank_person"=>$params["username"],
                        "bank_name"=>$params["bank_name"],
                        "bank_code"=>$params["bank_no"],
                        "updated_time"=>time()
                    ];
                    Db::name("user_bank")->where(["uid" => $t_uid])->update($bank_input);
                    Db::commit();
                    if ($op) {
                        $this->success();
                    } else {
                        Db::rollback();
                    }
                }
            }
            $this->error();
        }
        return $this->view->fetch();
    }


    /**
     * 审核派克
     */
    public function real()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post();

            //halt($params);
            if (!$params["uid"]) {
                renderJson("当前不可以添加", 0);
            }
            if ($params) {
                $_input_user = [
                    "after_safe_img" => $params["after_safe_img"],
                    "tao_gas_img" => $params["tao_gas_img"],
                    "tao_flower_img" => $params["tao_flower_img"],
                    "tao_exam_img" => $params["tao_exam_img"],
                    "tao_baby_img" => $params["tao_baby_img"],
                    "tao_evaluate_img" => $params["tao_evaluate_img"],
                    "real_status" => $params["real_status"]
                ];
                try {
                    if ($params["real_id"]) {
                        $this->user_real->where(["real_id" => $params["real_id"]])->setField($_input_user);
                    } else {
                        $_input_user["uid"] = $params["uid"];
                        $this->user_real->save($_input_user);
                    }
                    renderJson("成功", 1);
                } catch (\Exception $e) {
                    renderJson("失败", 0);
                }
            }
            renderJson("失败", 0);
        }


    }


    /**
     *
     *禁用启用,设置组长,加黑名单
     *
     */
    public function update_status()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $status = "";
            if ($params) {
                if($params["row"]["status"]==1 && $params["field"]=="status" && $params["row"]["real_status"]!=2){
                    renderJson("派克未通过,不可以禁用",0);
                }
                switch ($params["field"]) {
                    case "status":
                        $status = $params["row"]["status"] == 0 ? 1 : 0;
                        break;
                    case "black":
                        $status = $params["row"]["black"] == 1 ? 0 : 1;
                        break;
                    case "role":
                        $status = $params["row"]["role"] == "grouper" ? "user" : "grouper";
                        //组长
                        if($status=="user"){
                            renderJson("派克已经是组长,不可以更改了",0);
                        }
                        break;
                }
                try {
                    $pa = [
                        $params["field"] => $status
                    ];
                    //成为组长的时间
                    if($params["field"] == "role" && $status=="grouper") {
                        $pa["group_created_time"] = time();
                    }
                    $this->model->save($pa, ["uid" => $params["row"]["uid"]]);
                    if ($params["field"] == "status" && $status == 1) {
                        $uid = $params["row"]["uid"];
                        $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                        $msg = [
                            "condition" => 7,
                            "touser" => $openid,
                            "content" => ["您的账户已经由平台管理员给予通过"]
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                        //renderJson("修改成功",1);
                    }
                    if ($params["field"] == "status" && $status == 0) {
                        $uid = $params["row"]["uid"];
                        $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                        $msg = [
                            "condition" => 8,
                            "touser" => $openid,
                            "content" => ["您的账户已经由平台管理员给予禁用"]
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                        //renderJson("修改成功",1);
                    }

                    if ($params["field"] == "black" && $status == 0) {
                        $uid = $params["row"]["uid"];
                        $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                        $msg = [
                            "condition" => 7,
                            "touser" => $openid,
                            "content" => ["您的账户已经由平台管理员解开黑名单"]
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                    }
                    if ($params["field"] == "black" && $status == 1) {
                        $uid = $params["row"]["uid"];
                        $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                        $msg = [
                            "condition" => 8,
                            "touser" => $openid,
                            "content" => ["您的账户已经由平台管理员列为黑名单"]
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                        //renderJson("修改成功",1);
                    }
                    //renderJson("成功:" . json_encode($params), 1);
                    renderJson("成功操作", 1);
                } catch (\Exception $e) {
                    renderJson("失败", 0);
                }

            }
        }
    }

    /**
     * 禁用启用
     */
    public function isDisable(){
        if ($this->request->isPost()) {
            $params = $this->request->post();
            //$status = "";
            if ($params) {
                $this->func_status($params);
            }
        }
    }


    /**
     * 设置组长
     */
    public function isGroup(){
        if ($this->request->isPost()) {
            $params = $this->request->post();
            //$status = "";
            if ($params) {
                $this->func_status($params);
            }
        }
    }


    /**
     * 加黑名单
     */
    public function isBlack(){
        if ($this->request->isPost()) {
            $params = $this->request->post();
            //$status = "";
            if ($params) {
                $this->func_status($params);
            }
        }

    }




    /**
     * 修改用户参数
     *
     * type : 1
     * 账户余额修改
     *
     * type : 2
     *
     * 账号修改
     *
     * type ：3
     *
     * 绑定淘宝ID
     *
     *
     * type : 4
     *
     * 重置密码
     *
     *
     *
     *
     */
    public function edit_user($ids = NULL)
    {
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                try {
                    switch ($params["type"]) {
                        case 1://账户余额修改
                            if(floatval($params["value"])<=0){
                                //echo "aaa";exit;
                                renderJson("余额有误！",0);
                                //$this->error("余额有误!");
                            }
                            Db::name("user")->where("uid", $params["uid"])->setInc("balance", floatval($params["value"]));

                            $user_info = Db::name("user")->where("uid", $params["uid"])->find();

                            $insert_1 = array();
                            $insert_1["fina_type"] = "in";
                            $insert_1["obj_type"] = "sys";
                            $insert_1["obj_id"] = 0;
                            $insert_1["uid"] = $user_info["uid"];
                            $insert_1["username"] = $user_info["username"];
                            $insert_1["desc"] = "管理员添加的金豆";
                            $insert_1["order_id"] = "";
                            $insert_1["fina_cash"] = floatval($params["value"]);
                            $insert_1["fina_channel"] = 1;
                            $insert_1["balance"] = $user_info["balance"];
                            $insert_1["source"] = "paike";
                            $insert_1["remark"] = "管理员添加的金豆";
                            $insert_1["on_time"] = time();
                            Db::name("finance")->insert($insert_1);//添加财务表

                            $insert_2 = array();
                            $insert_2["fina_type"] = "out";
                            $insert_2["obj_type"] = "system_out";
                            $insert_2["obj_id"] = 0;
                            $insert_2["uid"] = 0;
                            $insert_2["username"] = "";
                            $insert_2["desc"] = "管理员添加的金豆系统扣除金豆";
                            $insert_2["order_id"] = "";
                            $insert_2["fina_cash"] = floatval($params["value"]);
                            $insert_2["fina_channel"] = 1;
                            $insert_2["balance"] = 0;
                            $insert_2["source"] = "system";
                            $insert_2["remark"] = "管理员添加的金豆系统扣除金豆";
                            $insert_2["on_time"] = time();
                            Db::name("finance")->insert($insert_2);//添加财务表
                            //$username = Db::name("user")->where("uid",$params["uid"])->field("username,mobile")->find();
                            $openid = Db::name("wx_users")->where("uid", $params["uid"])->value("openid");
                            $msg = [
                                "condition" => 16,
                                "touser" => $openid,
                                "content" => [floatval($params["value"]), "系统返回的金豆数！请查收！"]
                            ];
                            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                            $MiniMsg->sendMsg();//发送短信模板银行卡修改成功

                            break;
                        case 2://账号修改
                            $this->model->save(["mobile" => $params["mobile"]], ["uid" => $params["uid"]]);
                            break;
                        case 3://绑定淘宝ID
                            $this->model->save(["tao_bao_id" => $params["tao_bao_id"]], ["uid" => $params["uid"]]);
                            break;
                        case 4://重置密码
                            $auth = new Auth();
                            $sec_code = Random::alnum();
                            $password = $auth->getEncryptPassword("000000", $sec_code);
                            $this->model->save(["password" => $password, "sec_code" => $sec_code], ["uid" => $params["uid"]]);
                            break;
                    }
                    renderJson("成功", 1);
                    //$this->success("成功");
                } catch (\Exception $e) {
                    renderJson("失败", 0);
                    //$this->error("失败");
                    //echo $e->getMessage();exit;
                    //$this->error($e->getMessage());
                }
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", input("type"));
        return $this->view->fetch();
    }




    /**
     * @param 账户余额修改
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_balance($ids = NULL){
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $this->edit_user_act($ids,$params);
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", input("type"));
        return $this->view->fetch("edit_user");

    }


    /**
     * @param 账号修改
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_account($ids = NULL){
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $paike = $this->model
                    ->where(["mobile" => $params["mobile"]])
                    ->where("uid", "neq", $ids)
                    ->find();
                if ($paike) {
                    $this->error("手机，淘宝号，qq已注册");
                }
                $this->edit_user_act($ids,$params);
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", input("type"));
        return $this->view->fetch("edit_user");

    }


    /**
 * @param 绑定淘宝ID
 * @return string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
    public function edit_taobao($ids = NULL){
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $this->edit_user_act($ids,$params);
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", input("type"));
        return $this->view->fetch("edit_user");

    }



    /**
     * @param 重置密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_pass($ids = NULL){
        $row = $this->model->with('userAttribute,userReal,userHealthy,authReal')->field('*,uid as id')->find(['uid' => $ids]);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $this->edit_user_act($ids,$params);
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("type", input("type"));
        return $this->view->fetch("edit_user");

    }




    /**
     *
     * 批量禁用
     *
     */
    public function mult_no()
    {


        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            Db::name("user")->where("uid", "in", $ids)->update(["status" => 0]);
            renderJson("成功禁用", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     *
     * 批量启用
     */
    public function mult_pass()
    {
        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            Db::name("user")->where("uid", "in", $ids)->update(["status" => 1]);
            renderJson("成功通过", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     *
     * 批量锁定金额
     */
    public function mult_price()
    {
        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            Db::name("user_attribute")->where("uid", "in", $ids)->update(["account_status" => 2]);
            renderJson("成功锁定金额", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     *
     * 批量解开金额
     */
    public function mult_price_no()
    {
        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            Db::name("user_attribute")->where("uid", "in", $ids)->update(["account_status" => 1]);
            renderJson("成功解开金额", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     *
     * 上下线
     */
    public function upper($ids = NULL){


        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //echo $ids;exit;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $join[] = ["sd_user r", "r.uid = e.uid", "left"];
            $join[] = ["sd_user_real l","l.uid = e.uid","left"];
            $field = "e.*,r.role,r.tao_bao_no,l.real_status";
            $_where["e.parent_id"] = $ids;
            $total = Db::name("user_tree")
                ->alias("e")
                ->join($join)
                ->where($_where)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = Db::name("user_tree")
                ->alias("e")
                ->field($field)
                ->join($join)
                ->where($_where)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        //通过uid获取两级父id
        $user_tree = Db::name("user_tree")->where("uid",$ids)->find();
        $tree_where["tree_id"] = $user_tree["tree_id"];//根据当前树
        $tree_where["lft"] = array("<",$user_tree["lft"]);//左节点小于
        $tree_where["rgt"] = array(">",$user_tree["rgt"]);//大于右节点              -------------------根据level倒叙选两个
        $parent_list = Db::name("user_tree")->where("lft","<",$user_tree["lft"])->where("rgt",">",$user_tree["rgt"])->field("uid,username")->order("level DESC")->limit(3)->select();
        $this->view->assign("parent_list", $parent_list);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();

    }


    /**
     * 往来明细
     */
    public function finance($ids = NULL){

        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $join[] = ["sd_shop_order r","e.order_id = r.order_id","left"];

            $field = "e.*,e.fina_id as id,r.order_sno";

            $_where["e.uid"] = $ids;
            $total = Db::name("finance")
                ->alias("e")
                ->join($join)
                ->where($_where)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = Db::name("finance")
                ->alias("e")
                ->join($join)
                ->where($_where)
                ->where($where)
                ->field($field)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $finance_act = new \app\common\model\Finance();
            foreach ($list as &$value){
                $value["obj_type"] = $finance_act->getObjType()[$value["obj_type"]];
            }

            $result = array("total" => $total, "rows" => $list);


            return json($result);
        }
        $this->view->assign("ids", $ids);
        return $this->view->fetch();


    }


    /**
     *
     * 任务详情
     */
    public function task_info($ids = NULL){


        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //echo $ids;exit;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $_where["uid"] = $ids;
            $total = Db::name("shop_order")
                ->where($_where)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = Db::name("shop_order")
                ->where($_where)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign("ids", $ids);
        return $this->view->fetch();

    }



    /**
     *
     *禁用启用,设置组长,加黑名单公用方法
     *
     */
    public function func_status($params){
        $status = "";
        if($params["row"]["status"]==1 && $params["field"]=="status" && $params["row"]["real_status"]!=2){
            renderJson("派克未通过,不可以禁用",0);
        }
        switch ($params["field"]) {
            case "status":
                $status = $params["row"]["status"] == 0 ? 1 : 0;
                break;
            case "black":
                $status = $params["row"]["black"] == 1 ? 0 : 1;
                break;
            case "role":
                $status = $params["row"]["role"] == "grouper" ? "user" : "grouper";
                //组长
                if($status=="user"){
                    renderJson("派克已经是组长,不可以更改了",0);
                }
                break;
        }
        try {
            $pa = [
                $params["field"] => $status
            ];
            //成为组长的时间
            if($params["field"] == "role" && $status=="grouper") {
                $pa["group_created_time"] = time();
            }
            $this->model->save($pa, ["uid" => $params["row"]["uid"]]);
            if ($params["field"] == "status" && $status == 1) {
                $uid = $params["row"]["uid"];
                $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                $msg = [
                    "condition" => 7,
                    "touser" => $openid,
                    "content" => ["您的账户已经由平台管理员给予通过"]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                //renderJson("修改成功",1);
            }
            if ($params["field"] == "status" && $status == 0) {
                $uid = $params["row"]["uid"];
                $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                $msg = [
                    "condition" => 8,
                    "touser" => $openid,
                    "content" => ["您的账户已经由平台管理员给予禁用"]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                //renderJson("修改成功",1);
            }

            if ($params["field"] == "black" && $status == 0) {
                $uid = $params["row"]["uid"];
                $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                $msg = [
                    "condition" => 7,
                    "touser" => $openid,
                    "content" => ["您的账户已经由平台管理员解开黑名单"]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
            }
            if ($params["field"] == "black" && $status == 1) {
                $uid = $params["row"]["uid"];
                $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                $msg = [
                    "condition" => 8,
                    "touser" => $openid,
                    "content" => ["您的账户已经由平台管理员列为黑名单"]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                //renderJson("修改成功",1);
            }
            //renderJson("成功:" . json_encode($params), 1);
            renderJson("成功操作", 1);
        } catch (\Exception $e) {
            renderJson("失败", 0);
        }

    }


    /**
     * 编辑用户的公用方法
     */
    public function edit_user_act($ids = NULL,$params){
        try {
            switch ($params["type"]) {
                case 1://账户余额修改
                    if(floatval($params["value"])<=0){
                        //echo "aaa";exit;
                        renderJson("余额有误！",0);
                        //$this->error("余额有误!");
                    }
                    Db::name("user")->where("uid", $params["uid"])->setInc("balance", floatval($params["value"]));

                    $user_info = Db::name("user")->where("uid", $params["uid"])->find();

                    $insert_1 = array();
                    $insert_1["fina_type"] = "in";
                    $insert_1["obj_type"] = "sys";
                    $insert_1["obj_id"] = 0;
                    $insert_1["uid"] = $user_info["uid"];
                    $insert_1["username"] = $user_info["username"];
                    $insert_1["desc"] = "管理员添加的金豆";
                    $insert_1["order_id"] = "";
                    $insert_1["fina_cash"] = floatval($params["value"]);
                    $insert_1["fina_channel"] = 1;
                    $insert_1["balance"] = $user_info["balance"];
                    $insert_1["source"] = "paike";
                    $insert_1["remark"] = "管理员添加的金豆";
                    $insert_1["on_time"] = time();
                    Db::name("finance")->insert($insert_1);//添加财务表

                    $insert_2 = array();
                    $insert_2["fina_type"] = "out";
                    $insert_2["obj_type"] = "system_out";
                    $insert_2["obj_id"] = 0;
                    $insert_2["uid"] = 0;
                    $insert_2["username"] = "";
                    $insert_2["desc"] = "管理员添加的金豆系统扣除金豆";
                    $insert_2["order_id"] = "";
                    $insert_2["fina_cash"] = floatval($params["value"]);
                    $insert_2["fina_channel"] = 1;
                    $insert_2["balance"] = 0;
                    $insert_2["source"] = "system";
                    $insert_2["remark"] = "管理员添加的金豆系统扣除金豆";
                    $insert_2["on_time"] = time();
                    Db::name("finance")->insert($insert_2);//添加财务表
                    //$username = Db::name("user")->where("uid",$params["uid"])->field("username,mobile")->find();
                    $openid = Db::name("wx_users")->where("uid", $params["uid"])->value("openid");
                    $msg = [
                        "condition" => 16,
                        "touser" => $openid,
                        "content" => [floatval($params["value"]), "系统返回的金豆数！请查收！"]
                    ];
                    $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                    $MiniMsg->sendMsg();//发送短信模板银行卡修改成功

                    break;
                case 2://账号修改

                    $this->model->save(["mobile" => $params["mobile"]], ["uid" => $params["uid"]]);
                    break;
                case 3://绑定淘宝ID
                    $this->model->save(["tao_bao_id" => $params["tao_bao_id"]], ["uid" => $params["uid"]]);
                    break;
                case 4://重置密码
                    $auth = new Auth();
                    $sec_code = Random::alnum();
                    $password = $auth->getEncryptPassword("000000", $sec_code);
                    $this->model->save(["password" => $password, "sec_code" => $sec_code], ["uid" => $params["uid"]]);
                    break;
            }
            renderJson("成功", 1);
            //$this->success("成功");
        } catch (\Exception $e) {
            renderJson("失败", 0);
            //$this->error("失败");
            //echo $e->getMessage();exit;
            //$this->error($e->getMessage());
        }

    }








}
